﻿using Lis.Dto;
using Lis.IBLL;
using Lis.IRepository;
using Lis.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Lis.BLL
{
    public class AppointmentService:BaseService<AppointmentInfo>,IAppointmentService
    {
        #region 01,图书预约+ServiceResult<string> HoldBook(DTO.BorrowBookDto borrowBook)
        /// <summary>
        /// 图书预约
        /// </summary>
        /// <param name="borrowBook">预约Dto</param>
        /// <returns></returns>
        public ServiceResult<string> HoldBook(DTO.BorrowBookDto borrowBook)
        {
            //1，读者卡是否在有效期内
            //2，读者是否有预约权限-当前书的馆藏
            //3，当前书是否在馆（是否全部被借出）
            //4，读者是否已经预约过当前书
            //5，读者是否到达最大预约数量
            //6，是否达到改馆藏的最大预约数量
            //7，在日志表里面插数据
            //8，在YYB里面插入数据


            #region 1,验证读者卡号是否在有效期内  通过
            var user = ((IUserInfoRepository)(DBSession.SysUserInfoRepository)).GetById(borrowBook.UserName);

            if (user == null)//判断是否有这个人
            {
                return new ServiceResult<string>()
                {
                    Success = false,
                    Message = "查无此人，不能进行预约操作",
                    Code = "10001"
                };
            }
            if (user.YXRQ == null)//判断有效日期是否为null
            {
                return new ServiceResult<string>()
                {
                    Success = false,
                    Message = "该卡未设置有效日期，不能进行预约操作",
                    Code = "10002"
                };
            }
            if (!(DateTime.Now < user.YXRQ))//判断有效日期是否在有效范围内
            {
                return new ServiceResult<string>()
                {
                    Success = false,
                    Message = "该卡已过有效日期，不能进行预约操作",
                    Code = "10003"
                };
            }

            #endregion

            #region 2，判断书所在的馆藏地，根据馆藏地判断是否到达最大借阅数量  预约权限
            //获取图书的馆藏地代码  通过
            var bookDetail = ((IBookDetailRepository)DBSession.SysBookDetailRepository).GetEntitiesByBarCode(borrowBook.BarCode).First<BookDetail>();

            //获取该类型的读者的在馆藏地最大借阅数量  通过
            var userCirculateS = ((IUserCirculateRepository)DBSession.SysUserCirculateRepository).GetEntitiesByUserType(user.DZLX, bookDetail.DCDDM);

            if (userCirculateS != null && userCirculateS.Count()<=0)
            {
                return new ServiceResult<string>()
                {
                    Success = false,
                    Message = "未开通预约权限，不能进行预约",
                    Code = "10004"
                };
            }
            var userCirculate = userCirculateS.First();
             #endregion

            #region 3，当前书是否在馆（是否全部被借出）
            var bookStatus = ((IBookDetailRepository)DBSession.SysBookDetailRepository).GetEntitiesByDocNumber(bookDetail.KZH).Where<BookDetail>(u => u.TSZT == "1");
            if (bookStatus != null && bookStatus.Count() > 0)
            {
                return new ServiceResult<string>()
                {
                    Success = false,
                    Message = "该馆有在库的书刊，请直接借阅",
                    Code = "10005"
                };
            }

            #endregion

            #region 4，是否预约过该图书
            //根据预约图书和卡号筛选当前预约  通过
            var book_YY = ((IAppointmentInfoRepository)DBSession.SysAppointmentInfoRepository).GetEntitiesByUserName(borrowBook.UserName);
            if (book_YY == null && book_YY.Count() < 0)
            {
                return new ServiceResult<string>()
                {
                    Success = false,
                    Message = "该读者没有预约图书",
                    Code = "10006"
                };
            }
            var book_collection=book_YY.Where<AppointmentInfo>(u => string.IsNullOrEmpty(u.DSRQ));

            //判断当前人是否预约过此书了
            var book_collection_YY = book_collection.Where<AppointmentInfo>(u => u.DCTM == borrowBook.BarCode);

            if (book_collection_YY != null && book_collection_YY.Count() > 0)
            {
                return new ServiceResult<string>()
                {
                    Success = false,
                    Message = "该读者已预约过该图书，不能进行重复预约",
                    Code = "10007"
                };
            } 
            #endregion

            #region 5，判断是否到达该馆藏的最大预约数量
            //判断读者的最大预约数量是否已达上限  通过
            if (book_collection.Count() >= userCirculate.YYCS)
            {
                return new ServiceResult<string>()
                {
                    Success = false,
                    Message = "已到最大预约册数，不能进行预约操作",
                    Code = "10008"
                };
            }
            #endregion

            #region 6，是否达到改馆藏的最大预约数量
            //判断读者的该馆藏最大预约数量是否已达上限  通过
            var book_collection_YY_DCD = book_collection_YY.Where<AppointmentInfo>(u => u.DCD == bookDetail.DCDDM).ToList();
            if (book_collection_YY_DCD.Count() >= userCirculate.YYCS)
            {
                return new ServiceResult<string>()
                {
                    Success = false,
                    Message = "已到该馆藏最大预约册数，不能进行预约操作",
                    Code = "10009"
                };
            } 
            #endregion

          
            #region 7，在日志表里面插数据
            var log = new LogInfo()
            {
                DZTM = borrowBook.UserName,
                DCTM = borrowBook.BarCode,
                CZY = CirculateConfig.Operator,
                CZRQ = DateTime.Now,
                CZLXDM = "YY",
                SQLSTR = @"Insert into yyb(dztm,dctm,yyrq,lyb,dclx,dcd,gcdwdm,kzh,jq,marc) values ('"+borrowBook.UserName+"','"+borrowBook.BarCode+"',TO_DATE('"+DateTime.Now.ToString("yyyy-mm-dd hh:MM:ss")+"','YYYY-MM-DD HH24:MI:SS'),'zykdck','0001','"+bookDetail.DCDDM+"','1','"+bookDetail.KZH+"','','U')",
                LYB = "zydck",
                MARC = "U",
                GCDWDM = "1"
            };
            if (DBSession.SysLogInfoRepository.Add(log))
            #endregion
            {
                #region 8，在YYB里面插入数据   在Dal里面重新开方法
                var appointmentInfo = new AppointmentInfo()
                {
                    DZTM=borrowBook.UserName,
                    DCTM=borrowBook.BarCode,
                    YYRQ=DateTime.Now,
                    JCRQ=null,
                    LYB = "zykdck",
                    KZH=bookDetail.KZH,
                    MARC="U",
                    DCLX="0001",
                    DCD=bookDetail.DCDDM,
                    GCDWDM="1",
                    CZY =CirculateConfig.Operator
                };
                if (DBSession.SysAppointmentInfoRepository.Add(appointmentInfo))
                {
                    return new ServiceResult<string>()
                    {
                        Success = true,
                        Message = "预约成功",
                        Code = "10000"
                    };
                }
                else
                {
                    return new ServiceResult<string>()
                    {
                        Success = false,
                        Message = "操作失败，请重新进行预约",
                        Code = "10010"
                    };
                }
            }
            else
            {
                return new ServiceResult<string>()
                {
                    Success = false,
                    Message = "操作失败，请重新进行预约",
                    Code = "10011"
                };
            }
                #endregion
        } 
        #endregion

        #region 02，取消图书预约+ServiceResult<string> CancelHoldBook(DTO.BorrowBookDto borrowBook)
        /// <summary>
        /// 取消图书预约
        /// </summary>
        /// <param name="borrowBook">预约Dto</param>
        /// <returns></returns>
        public ServiceResult<string> CancelHoldBook(DTO.BorrowBookDto borrowBook)
        {
            //1，读者卡是否在有效期内
            //2,图书是否被预约
            //3，在日志表里面插数据
            //4，在YYB里面删除数据


            #region 1,验证读者卡号是否在有效期内  通过
            var user = ((IUserInfoRepository)(DBSession.SysUserInfoRepository)).GetById(borrowBook.UserName);

            if (user == null)//判断是否有这个人
            {
                return new ServiceResult<string>()
                {
                    Success = false,
                    Message = "查无此人，不能进行借阅操作",
                    Code = "10001"
                };
            }
            if (user.YXRQ == null)//判断有效日期是否为null
            {
                return new ServiceResult<string>()
                {
                    Success = false,
                    Message = "该卡未设置有效日期，不能进行借阅操作",
                    Code = "10002"
                };
            }
            if (!(DateTime.Now < user.YXRQ))//判断有效日期是否在有效范围内
            {
                return new ServiceResult<string>()
                {
                    Success = false,
                    Message = "该卡已过有效日期，不能进行借阅操作",
                    Code = "10003"
                };
            }

            #endregion

            #region 2，判断当前人是否预约过此书了
            //判断当前人是否预约过此书了

            //根据预约图书和卡号筛选当前预约  通过
            var book_collection = ((IAppointmentInfoRepository)DBSession.SysAppointmentInfoRepository).GetEntitiesByUserName(borrowBook.UserName).Where<AppointmentInfo>(u => string.IsNullOrEmpty(u.DSRQ));

            var book_collection_YY = book_collection.Where<AppointmentInfo>(u => u.DCTM == borrowBook.BarCode).ToList();

            if (book_collection_YY != null && book_collection_YY.Count() < 0)
            {
                return new ServiceResult<string>()
                {
                    Success = false,
                    Message = "该书不是你预约的，不能进行取消预约操作",
                    Code = "10004"
                };
            } 
            #endregion

            #region 3，在日志表里面插数据
            var log = new LogInfo()
            {
                DZTM = borrowBook.UserName,
                DCTM = borrowBook.BarCode,
                CZY = CirculateConfig.Operator,
                CZRQ = DateTime.Now,
                CZLXDM = "JY",
                SQLSTR = @"delete from yyb where (dztm = '"+borrowBook.UserName+"') and (dctm = '"+borrowBook.BarCode+"')",
                LYB = "zydck",
                MARC = "U",
                GCDWDM = "1"
            };
            if (DBSession.SysLogInfoRepository.Add(log))
            #endregion
            {
                #region 4，在YYB里面删除数据   在Dal里面重新开方法
                var appointmentInfo = new AppointmentInfo()
                {
                    DZTM = borrowBook.UserName,
                    DCTM = borrowBook.BarCode,
                };
                if (DBSession.SysAppointmentInfoRepository.Delete(appointmentInfo))
                {
                    return new ServiceResult<string>()
                    {
                        Success = true,
                        Message = "取消成功",
                        Code = "10000"
                    };
                }
                else
                {
                    return new ServiceResult<string>()
                    {
                        Success = false,
                        Message = "操作失败，请重新进行取消预约",
                        Code = "10005"
                    };
                }
            }
            else
            {
                return new ServiceResult<string>()
                {
                    Success = false,
                    Message = "操作失败，请重新进行取消预约",
                    Code = "10006"
                };
            }
                #endregion
        } 
        #endregion

        #region 03，获取当前预约记录+ServiceResult<IEnumerable<object>> GetEntitiesByUserName(string UserName)
        /// <summary>
        /// 获取当前预约记录
        /// </summary>
        /// <param name="UserName">读者卡号</param>
        /// <returns></returns>
        public ServiceResult<IEnumerable<object>> GetEntitiesByUserName(string UserName)
        {
            if (!string.IsNullOrEmpty(UserName))
            {
                return new ServiceResult<IEnumerable<object>>()
                {
                    Success = true,
                    Result = ((IAppointmentRepository)DBSession.SysAppointmentRepository).GetEntitiesByUserName(UserName),
                    Message = "",
                    Code = "10000"
                };
            }
            else
            {
                return new ServiceResult<IEnumerable<object>>()
                {
                    Success = false,
                    Result = null,
                    Message = "请输入正确的读者卡号进行查询",
                    Code = "10001"
                };
            }
        } 
        #endregion
        #region 04，分页查询+override IQueryable<AppointmentInfo> GetPageEntities<S>(int pageSize, int pageIndex, out int total, bool isAsc, System.Linq.Expressions.Expression<Func<AppointmentInfo, bool>> whereLambda, System.Linq.Expressions.Expression<Func<AppointmentInfo, S>> orderByLambda)
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <typeparam name="S"></typeparam>
        /// <param name="pageSize">页大小</param>
        /// <param name="pageIndex">页码</param>
        /// <param name="total">总条数</param>
        /// <param name="isAsc">是否倒序</param>
        /// <param name="whereLambda">查询lambda</param>
        /// <param name="orderByLambda">排序lambda</param>
        /// <returns></returns>
        public override IQueryable<AppointmentInfo> GetPageEntities<S>(int pageSize, int pageIndex, out int total, bool isAsc, System.Linq.Expressions.Expression<Func<AppointmentInfo, bool>> whereLambda, System.Linq.Expressions.Expression<Func<AppointmentInfo, S>> orderByLambda)
        {
            throw new NotImplementedException();
        } 
        #endregion

        public override bool Add(AppointmentInfo entity)
        {
            throw new NotImplementedException();
        }

        public override bool UpDate(AppointmentInfo entity)
        {
            throw new NotImplementedException();
        }

        public override bool Delete(AppointmentInfo entity)
        {
            throw new NotImplementedException();
        }
    }
}
